/*
 * jPSXdec: Playstation 1 Media Decoder/Converter in Java
 * Copyright (C) 2007-2008  Michael Sabin
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor,   
 * Boston, MA  02110-1301, USA.
 *
 */

/*
 * SaveTIM.java
 */

package jpsxdec;

import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import jpsxdec.media.Tim;
import jpsxdec.media.savers.Formats;
import jpsxdec.util.Misc;

public class SaveTIM extends javax.swing.JDialog {
    
    private Tim m_oTim;
    TIMPaletteCheck[] m_oPreviews;
    BufferedImage[] m_oBufImgs;
    
    private String m_sBaseName;
    
    /** Creates new form SaveTIM */
    public SaveTIM(JFrame owner, Tim tim, String suggestedName) {
        super(owner, true);
        initComponents();
        this.setLocationRelativeTo(owner);
        
        m_oTim = tim;
        
        m_sBaseName = suggestedName;
        
        int iPals = m_oTim.getPaletteCount();
        
        m_oPreviews = new TIMPaletteCheck[iPals];
        m_oBufImgs = new BufferedImage[iPals];
        
        GridLayout gl = (GridLayout) panelImages.getLayout();
        gl.setRows((int)Math.floor(Math.sqrt(iPals)));
        gl.setColumns((int)Math.ceil(Math.sqrt(iPals)));
            
        for (int i = 0; i < iPals; i++) {
            m_oBufImgs[i] = m_oTim.toBufferedImage(i);
            m_oPreviews[i] = new TIMPaletteCheck(m_oBufImgs[i], i);
            panelImages.add(m_oPreviews[i]);
        }
        
        cmbFormat.setModel(new DefaultComboBoxModel( Formats.getAllJavaImgFormats() ));
        lblSizeValue.setText(m_oTim.getWidth() + " x " + m_oTim.getHeight());
        
        txtFolder.setText(new File("").getAbsolutePath());
        
        this.pack();

        updateGui();
    }
    
    private void updateGui() {
        Object sel = cmbFormat.getSelectedItem();
        Formats.Format vidfmt =(Formats.Format)sel;
        txtFileName.setText(m_sBaseName + "." + vidfmt.getExt());
        
        boolean blnJpgEnabled = cmbFormat.getSelectedItem() == Formats.JPEG_IMG_SEQ;
                
        slideJpegQuality.setEnabled(blnJpgEnabled);
        txtJpegQuality.setEnabled(blnJpgEnabled);
        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        boundedRangeDocumentModel1 = new jpsxdec.BoundedRangeDocumentModel();
        txtFolder = new javax.swing.JTextField();
        lblFolder = new javax.swing.JLabel();
        btnBrowse = new javax.swing.JButton();
        panelImages = new javax.swing.JPanel();
        cmbFormat = new javax.swing.JComboBox();
        btnSave = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        txtFileName = new javax.swing.JTextField();
        lblFormat = new javax.swing.JLabel();
        lblFileName = new javax.swing.JLabel();
        lblSize = new javax.swing.JLabel();
        lblSizeValue = new javax.swing.JLabel();
        slideJpegQuality = new javax.swing.JSlider();
        lblJpegQuality = new javax.swing.JLabel();
        txtJpegQuality = new javax.swing.JTextField();
        btnSelectAll = new javax.swing.JButton();
        btnSelectNone = new javax.swing.JButton();

        boundedRangeDocumentModel1.setValue(75);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lblFolder.setText("Folder:");

        btnBrowse.setText("Browse...");
        btnBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBrowseActionPerformed(evt);
            }
        });

        panelImages.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        panelImages.setLayout(new java.awt.GridLayout(1, 4));

        cmbFormat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbFormatActionPerformed(evt);
            }
        });

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnClose.setText("Close");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        txtFileName.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtFileNameFocusLost(evt);
            }
        });

        lblFormat.setText("Format:");

        lblFileName.setText("File name:");

        lblSize.setText("Size:");

        lblSizeValue.setText("16 x 16");

        slideJpegQuality.setMinorTickSpacing(25);
        slideJpegQuality.setPaintTicks(true);
        slideJpegQuality.setModel(boundedRangeDocumentModel1);

        lblJpegQuality.setText("JPEG quality:");

        txtJpegQuality.setDocument(boundedRangeDocumentModel1);

        btnSelectAll.setText("Select all");
        btnSelectAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectAllActionPerformed(evt);
            }
        });

        btnSelectNone.setText("Select none");
        btnSelectNone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectNoneActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, panelImages, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(14, 14, 14)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, lblFileName)
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, lblFormat)
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, lblSize)))
                            .add(lblJpegQuality))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, lblSizeValue)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                                .add(slideJpegQuality, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(txtJpegQuality, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 42, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(org.jdesktop.layout.GroupLayout.LEADING, cmbFormat, 0, 202, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, txtFileName, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)))
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(lblFolder)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(txtFolder, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 245, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnBrowse))
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(btnSelectAll)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnSelectNone)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 47, Short.MAX_VALUE)
                        .add(btnClose, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 74, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnSave, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 71, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblFolder)
                    .add(btnBrowse)
                    .add(txtFolder, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblSize)
                    .add(lblSizeValue))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblFormat)
                    .add(cmbFormat, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(4, 4, 4)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
                    .add(lblJpegQuality)
                    .add(slideJpegQuality, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(txtJpegQuality, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblFileName)
                    .add(txtFileName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnSelectAll)
                    .add(btnSelectNone)
                    .add(btnSave)
                    .add(btnClose))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(panelImages, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseActionPerformed
        JFileChooser fc = new BetterFileChooser(".");
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int ret = fc.showOpenDialog(this);
        if (ret == JFileChooser.APPROVE_OPTION) {
            txtFolder.setText(fc.getSelectedFile().toString());
        }
    }//GEN-LAST:event_btnBrowseActionPerformed

    private void btnSelectAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectAllActionPerformed
        for (TIMPaletteCheck pal : m_oPreviews) {
            pal.setChecked(true);
        }
    }//GEN-LAST:event_btnSelectAllActionPerformed

    private void btnSelectNoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectNoneActionPerformed
        for (TIMPaletteCheck pal : m_oPreviews) {
            pal.setChecked(false);
        }        
    }//GEN-LAST:event_btnSelectNoneActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_btnCloseActionPerformed

    private void cmbFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbFormatActionPerformed
        updateGui();
    }//GEN-LAST:event_cmbFormatActionPerformed

    private void txtFileNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFileNameFocusLost
        m_sBaseName = Misc.getBaseName(txtFileName);
    }//GEN-LAST:event_txtFileNameFocusLost

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        try {
        
            int iCount = 0;
            for (TIMPaletteCheck pal : m_oPreviews) {
                if (pal.getChecked()) iCount++;
            }

            if (iCount < 1) {
                JOptionPane.showMessageDialog(this, "No TIM palettes selected to save.");
                return;
            } 

            Object sel = cmbFormat.getSelectedItem();
            Formats.Format vidfmt =(Formats.Format)sel;
            String sFormat = vidfmt.getId();

            String sFldr = txtFolder.getText();
            
            for (int i = 0; i < m_oBufImgs.length; i++) {
                if (m_oPreviews[i].getChecked()) {
                    BufferedImage bi = m_oBufImgs[i];
                    String sFile = String.format("%s%02d.%s",
                        Misc.getBaseName(txtFileName), i, Misc.getExt(txtFileName));
                    boolean bln = ImageIO.write(bi, sFormat, new File(sFldr, sFile));
                    if (!bln) throw new IOException("Unable to save image as " + sFormat);
                }
            }

            JOptionPane.showMessageDialog(this, "Images saved.");
        
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.toString());
        }

        
    }//GEN-LAST:event_btnSaveActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private jpsxdec.BoundedRangeDocumentModel boundedRangeDocumentModel1;
    private javax.swing.JButton btnBrowse;
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSelectAll;
    private javax.swing.JButton btnSelectNone;
    private javax.swing.JComboBox cmbFormat;
    private javax.swing.JLabel lblFileName;
    private javax.swing.JLabel lblFolder;
    private javax.swing.JLabel lblFormat;
    private javax.swing.JLabel lblJpegQuality;
    private javax.swing.JLabel lblSize;
    private javax.swing.JLabel lblSizeValue;
    private javax.swing.JPanel panelImages;
    private javax.swing.JSlider slideJpegQuality;
    private javax.swing.JTextField txtFileName;
    private javax.swing.JTextField txtFolder;
    private javax.swing.JTextField txtJpegQuality;
    // End of variables declaration//GEN-END:variables
    
}
